package com.mind.customer.handler.zhenghua;

import com.alibaba.fastjson2.JSONObject;
import com.mind.api.ShareAPI;
import com.mind.api.vo.OrderInfoResponse;
import com.mind.customer.api.oss.OSSUtils;
import com.mind.customer.config.FileConfig;
import com.mind.customer.domain.vo.TaskResult;
import com.mind.customer.exception.AjObjectNotFoundException;
import com.mind.customer.handler.Handler;
import com.mind.customer.handler.tongwei.BillOrderHandler;
import com.mind.customer.handler.tongwei.CheckHandler;
import com.mind.customer.handler.tongwei.OCRHandler;
import com.mind.customer.mapper.AjReportResultMapper;
import com.mind.system.mapper.AttachResultMapper;
import com.mind.customer.utils.CateUtils;
import com.mind.customer.utils.OrgUtils;
import com.mind.customer.utils.TaskUtils;
import com.mind.system.domain.AjReportResult;
import com.mind.system.domain.AjTicketTask;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单据处理器
 */
@Component("formalTicketHandler")
@Log4j2
public class TicketHandler implements Handler {


    @Resource
    private ShareAPI shareAPIUtils;

    @Resource
    private OrgUtils orgUtils;

    @Resource
    private AjReportResultMapper reportResultMapper;

    @Resource
    private CheckHandler checkHandler;

    @Resource
    private OCRHandler ocrHandler;

    @Resource
    private BillOrderHandler billOrderHandler;

    @Resource
    private ZhengHuaInvoiceHandler zhengHuaInvoiceHandler;

    @Resource
    private AttachResultMapper attachResultMapper;


    @Resource
    private FileConfig fileConfig;

    @Resource
    private OSSUtils ossUtils;

    @Resource
    private CateUtils cateUtils;

    /**
     * 单据处理器
     *
     * @param task
     * @return
     * @throws Exception
     * @throws AjObjectNotFoundException
     */
    public TaskResult handler(AjTicketTask task) throws Exception, AjObjectNotFoundException {
        TaskResult result = new TaskResult() {{
            setStatus(1);
        }};
        // 非标数据
        TaskResult ocrResult = null;
        // 发票数据
        TaskResult invoiceResult = null;
        // 原单数据
        TaskResult billOrderResult = null;
        if (!TaskUtils.isOnlyCheck(task)) {// tigger为0时才处理NC、OCR
            JSONObject info = JSONObject.parseObject(task.getInfo());
            if (info != null) {
                List<OrderInfoResponse.FileList> fileList = null;
                try {
                    // 获取原始附件V1.1.1开始
                    fileList = info.getList("Attachments", OrderInfoResponse.FileList.class);
                } catch (Exception e) {
                    log.error("解析附件文件错误:{}", info, e);
                }
                if (fileList != null) {
                    try {
                        log.info("OCR数据处理中...");
                        // 20250306改成多文件传NC
                        //packageSaveAttachResult(task, fileList);
                        ocrResult = ocrHandler.handler(task, fileList);
                        if (ocrResult.getStatus() == 2) {
                            return ocrResult;
                        }
                    } catch (Exception e) {
                        log.error("OCR处理异常：", e);
                    }
                }
            }
        }else{// 20250323add 仅触发查验需要把附件信息移动过来
            attachResultMapper.selectAttachList(task.getTicketId(), task.getVersion()-1).forEach(attachResult -> {
                attachResult.setVersion(task.getVersion());
                attachResultMapper.insertAttachResult(attachResult);
            });

        }
        try {
            log.info("原单数据处理中...");
            billOrderResult = billOrderHandler.handler(task, null);
            if (billOrderResult.getStatus() == 2) {
                return billOrderResult;
            }
        } catch (Exception e) {
            log.error("原单处理异常：", e);
        }
        // 保存
        packageSave(task, ocrResult, invoiceResult, billOrderResult);
        //检查
        checkHandler.handle(task);
        return result;
    }



    /**
     * 打包并保存
     *
     * @param task
     * @param ocrResult
     * @param invoiceResult
     * @param billOrderResult
     */
    private void packageSave(AjTicketTask task, TaskResult ocrResult, TaskResult invoiceResult, TaskResult billOrderResult) {
        Map<String, Object> handlerResult = new HashMap<>();
        Map<String, Object> originalResult = new HashMap<>();
        if (ocrResult != null && ocrResult.getData() != null) {
            handlerResult.putAll(ocrResult.getData());
            originalResult.putAll(ocrResult.getOriginalData());
        }
        if (invoiceResult != null && invoiceResult.getData() != null) {
            handlerResult.putAll(invoiceResult.getData());
            originalResult.putAll(invoiceResult.getOriginalData());
        }
        if (billOrderResult != null && billOrderResult.getData() != null) {
            originalResult.putAll(billOrderResult.getOriginalData());
            handlerResult.putAll(billOrderResult.getData());
        }
        // 如果是只触发规则检查直接拿上一次的
        if (TaskUtils.isOnlyCheck(task)) {
            AjReportResult reportResult = reportResultMapper.selectReportResultByTicketId(task.getTicketId(), task.getVersion() - 1);
            // 20250321add
            if(reportResult!=null) {
                handlerResult = JSONObject.parseObject(reportResult.getResult());
                originalResult = JSONObject.parseObject(reportResult.getOriginalResult());
            }
        }
        AjReportResult reportResult = reportResultMapper.selectReportResultByTicketId(task.getTicketId(), task.getVersion());
        if (reportResult == null) {
            reportResult = new AjReportResult();
            reportResult.setName(task.getTicketType() + "-" + task.getTicketId());
            reportResult.setReportId(task.getTicketId());
            reportResult.setTicketType(task.getTicketType());
            reportResult.setOrgId(task.getOrgId());
            reportResult.setVersion(task.getVersion());
            reportResult.setResult(JSONObject.toJSONString(handlerResult));
            reportResult.setOriginalResult(JSONObject.toJSONString(originalResult));
            reportResultMapper.insertReportResult(reportResult);
        } else {
            reportResult.setResult(JSONObject.toJSONString(handlerResult));
            reportResult.setOriginalResult(JSONObject.toJSONString(originalResult));
            reportResultMapper.updateReportResult(reportResult);
        }
    }


}
